package com.westvalley.syn.service;


import java.util.Iterator;
import java.util.Map;


import weaver.hrm.resource.ResourceComInfo;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONArray;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import com.westvalley.common.kit.MD5Kit;
import com.westvalley.common.kit.SqlsKit;
import com.westvalley.common.kit.StringKit;
import com.westvalley.common.kit.SqlsKit.SqlOperateType;
import com.westvalley.common.result.SqlResult;
import com.westvalley.service.cache.HrEducationLevelCache;
import com.westvalley.service.cache.HrJobTitleCache;
import com.westvalley.service.cache.HrResourceCache;
import com.westvalley.service.cache.OrgDepartmentCache;
import com.westvalley.service.callback.HrmResourceMaxId_Get;

import com.westvalley.syn.bean.Result;

/**
 * 人员信息同步
 * @author mos
 *
 */
public class HrResourceService extends SynService{
	private static final String KEY = "emp";
	private HrResourceCache resourceCache = HrResourceCache.me();
	private HrEducationLevelCache educattiionLevelCache = HrEducationLevelCache.me();
	private OrgDepartmentCache departmentCache = OrgDepartmentCache.me();
	private HrJobTitleCache jobTitleCache = HrJobTitleCache.me();
	public HrResourceService(){
		refreshCache();
		this.url = prop.getPropValue(KEY);
	}
	
	@Override
	protected void initParams(Map<String, String> params) {
		params.put("shopId", "TH05");
	}
	
	@Override
	protected Result synMainData(JSONArray jsonArrData) {
		Iterator<Object> it;
		if(jsonArrData!=null && (it=jsonArrData.iterator())!=null){
			SqlResult sqlResultInsert = SqlResult.me();
			SqlResult sqlResultUpdate = SqlResult.me();
			while (it.hasNext()) {
				JSONObject ob = (JSONObject) it.next();
				if( ob!=null ){
					String id = ob.getString("id");//人员编码
					if( StrKit.notBlank(id) ){
						Record resourseRecord = this.resourceCache.getRecordByCode(id);//缓存中人员信息
						if( resourseRecord==null ){
							sqlResultInsert.set(insertData(id,ob));
						}else{
							sqlResultUpdate.set(updateData(id,ob));
						}
					}else{
						return Result.me(new RuntimeException("数据主键为空！"));
					}
				}
			}
			int[] insertNums = sqlResultInsert.batch(500);
			int[] updateNums = sqlResultUpdate.batch(500);
			return Result.me(jsonArrData.size(),insertNums,updateNums);
		}else{
			return Result.me(new RuntimeException("接口数据为空无法同步！"));
		}
		
	}
	
	@Override
	protected Result synpOtherData(Result result, JSONArray jsonArrData) {
		SqlResult sqlResultInsert = SqlResult.me();
		sqlResultInsert.set(deleteOtherInfo());
		for(int i=0;i<jsonArrData.size();i++){
			JSONObject ob = jsonArrData.getJSONObject(i);
			if( ob!=null ){
				String id = ob.getString("id");//人员编码
				if(StrKit.notBlank(id)){
					//sqlResultInsert.set(updateManagerid(id,ob));
					sqlResultInsert.set(insertOtherInfo(id,ob));
				}
			}
		}
		sqlResultInsert.batch(500);
		return result;
	}
		
	/**
	 * 人员基础信息新增数据
	 * @param pk
	 * @param ob
	 * @return
	 */
	private SqlsKit insertData(String id, JSONObject ob) {
		SqlsKit sqlsKit = SqlsKit.me();
		sqlsKit.clear();			
		sqlsKit.setTableName("HrmResource");
//		学历  匹配 过程 0:初中 1:高中 2:中技  3:中专 4:大专 5:本科 6:硕士 7:博士 8:其它 
		String educ = StringKit.null2Str(ob.getString("educ"));
		String educationlevel = "";
		Record record = this.educattiionLevelCache.getRecordByCode(educ);
		if(record!=null)
			educationlevel = StringKit.null2o(record.get("id"));
		sqlsKit.addData("educationlevel", educationlevel);						//学历
		sqlsKit.addData("workcode", StringKit.null2Str(ob.getString("id")));	//员工编号
		sqlsKit.addData("loginid", StringKit.null2Str(ob.getString("userId")));	//登录账号
		sqlsKit.addData("lastname", StringKit.null2Str(ob.getString("name")));	//姓名
		sqlsKit.addData("password", MD5Kit.encodeMD5("1"));						//密码
		String sexCode = "0";
		String sex = StringKit.null2Str(ob.getString("sex"));
		if(StringKit.equals(sex, "男")) sexCode="0"; else sexCode="1";
		sqlsKit.addData("sex", sexCode);		//性别
//		部门ID需要处理，插入到OA的部门表里
		String officeid = StringKit.null2Str(ob.getString("officeId"));
		Record departmentIdRecord = this.departmentCache.getRecordByCode(officeid);
		String subcompanyid1 = "";
		String departmentId = "";
		if(departmentIdRecord!=null){
			subcompanyid1 = StringKit.null2o(departmentIdRecord.get("subcompanyid1"));
			departmentId = StringKit.null2o(departmentIdRecord.get("id"));
		}
		sqlsKit.addData("subcompanyid1", subcompanyid1);					//分部
		sqlsKit.addData("departmentid", departmentId);						//部门
//		岗位需要关联hrmjobtitle表的字段
		String sysdtid = StringKit.null2Str(ob.getString("postId"));			//岗位
		Record sysdtidRecord = this.jobTitleCache.getRecordByCode(sysdtid);
		String jobTitle = "";
		if(sysdtidRecord!=null){
			jobTitle = StringKit.null2o(sysdtidRecord.get("id"));
		}
		sqlsKit.addData("jobtitle", jobTitle);
		sqlsKit.addData("createdate", StringKit.getCurrentDate());//创建时间
		sqlsKit.addData("lastmoddate", StringKit.getCurrentDate());//最后修改时间
		
		String state = StringKit.null2Str(ob.getString("state"));
		String stateCode = "7";
//		判断状态，根据状态去改成相应的值  试用  正式  离职 	 
		if(StringKit.equals(state, "试用"))
			stateCode = "0";
		else if(StringKit.equals(state, "正式"))
			stateCode = "0";
		else
			stateCode = "5";
		sqlsKit.addData("status", stateCode);//离职状态
		sqlsKit.addData("mobile", StringKit.null2Str(ob.getString("telphone")));			//移动电话
		sqlsKit.addData("telephone", StringKit.null2Str(ob.getString("officeTel")));		//办公室电话
		sqlsKit.addData("email", StringKit.null2Str(ob.getString("email")));				//邮箱
		sqlsKit.addData("birthday", StringKit.null2Str(ob.getString("birthday")));			//出生日期
		sqlsKit.addData("folk", StringKit.null2Str(ob.getString("nation")));				//民族
		sqlsKit.addData("nativeplace", StringKit.null2Str(ob.getString("place")));			//籍贯
		sqlsKit.addData("certificatenum", StringKit.null2Str(ob.getString("idcard")));		//身份证号码
		sqlsKit.addData("bememberdate", StringKit.null2Str(ob.getString("indate")));		//入职日期
		sqlsKit.addData("systemlanguage", "7");												//系统语言
		//婚姻状况
		String marriage = StringKit.null2Str(ob.getString("marriage"));
		String maritalstatus = "0";
		if(StringKit.equals(marriage, "已婚"))
			maritalstatus = "1";
		else
			maritalstatus = "0";
		sqlsKit.addData("maritalstatus", maritalstatus);
		sqlsKit.addData("seclevel", StringKit.null2Str(ob.getString("saleLevel")));			//安全级别  
		String pid = Db.execute(new HrmResourceMaxId_Get()).toString();						//OA人员id
		sqlsKit.addData("id", pid);
		sqlsKit.setOperateType(SqlOperateType.INSERT);
		return sqlsKit;
	}
	/**
	 * 人员基础信息更新数据
	 * @param pk
	 * @param ob
	 * @return
	 */
	private SqlsKit updateData(String id, JSONObject ob) {
		SqlsKit sqlsKit = SqlsKit.me();
		sqlsKit.clear();			
		sqlsKit.setTableName("HrmResource");
//		学历  匹配 过程 0:初中 1:高中 2:中技  3:中专 4:大专 5:本科 6:硕士 7:博士 8:其它 
		String educ = StringKit.null2Str(ob.getString("educ"));
		String educationlevel = "";
		Record record = this.educattiionLevelCache.getRecordByCode(educ);
		if(record!=null)
			educationlevel = StringKit.null2o(record.get("id"));
		sqlsKit.addData("educationlevel", educationlevel);						//学历
		sqlsKit.addData("loginid", StringKit.null2Str(ob.getString("userId")));	//登录账号
		sqlsKit.addData("lastname", StringKit.null2Str(ob.getString("name")));	//姓名
		//sqlsKit.addData("password", MD5Kit.encodeMD5("1"));					//密码
		String sexCode = "0";
		String sex = StringKit.null2Str(ob.getString("sex"));
		if(StringKit.equals(sex, "男")) sexCode="0"; else sexCode="1";
		sqlsKit.addData("sex", sexCode);		//性别
//		部门ID需要处理，插入到OA的部门表里
		String officeid = StringKit.null2Str(ob.getString("officeId"));
		Record departmentIdRecord = this.departmentCache.getRecordByCode(officeid);
		String subcompanyid1 = "";
		String departmentId = "";
		if(departmentIdRecord!=null){
			subcompanyid1 = StringKit.null2o(departmentIdRecord.get("subcompanyid1"));
			departmentId = StringKit.null2o(departmentIdRecord.get("id"));
		}
		sqlsKit.addData("subcompanyid1", subcompanyid1);					//分部
		sqlsKit.addData("departmentid", departmentId);						//部门
//		岗位需要关联hrmjobtitle表的字段
		String sysdtid = StringKit.null2Str(ob.getString("postId"));			//岗位
		Record sysdtidRecord = this.jobTitleCache.getRecordByCode(sysdtid);
		String jobTitle = "";
		if(sysdtidRecord!=null){
			jobTitle = StringKit.null2o(sysdtidRecord.get("id"));
		}
		sqlsKit.addData("jobtitle", jobTitle);
		
		//sqlsKit.addData("createdate", StringKit.getCurrentDate());						//创建时间
		sqlsKit.addData("lastmoddate", StringKit.getCurrentDate());							//最后修改时间
		
		String state = StringKit.null2Str(ob.getString("state"));
		String stateCode = "7";
//		判断状态，根据状态去改成相应的值  试用  正式  离职 	 
		if(StringKit.equals(state, "试用"))
			stateCode = "0";
		else if(StringKit.equals(state, "正式"))
			stateCode = "0";
		else
			stateCode = "5";
		sqlsKit.addData("status", stateCode);												//离职状态
		sqlsKit.addData("mobile", StringKit.null2Str(ob.getString("telphone")));			//移动电话
		sqlsKit.addData("telephone", StringKit.null2Str(ob.getString("officeTel")));		//办公室电话
		sqlsKit.addData("email", StringKit.null2Str(ob.getString("email")));				//邮箱
		sqlsKit.addData("birthday", StringKit.null2Str(ob.getString("birthday")));			//出生日期
		sqlsKit.addData("folk", StringKit.null2Str(ob.getString("nation")));				//民族
		sqlsKit.addData("nativeplace", StringKit.null2Str(ob.getString("place")));			//籍贯
		sqlsKit.addData("certificatenum", StringKit.null2Str(ob.getString("idcard")));		//身份证号码
		sqlsKit.addData("bememberdate", StringKit.null2Str(ob.getString("indate")));		//入职日期
		sqlsKit.addData("systemlanguage", "7");												//系统语言
		//婚姻状况
		String marriage = StringKit.null2Str(ob.getString("marriage"));
		String maritalstatus = "0";
		if(StringKit.equals(marriage, "已婚"))
			maritalstatus = "1";
		else
			maritalstatus = "0";
		sqlsKit.addData("maritalstatus", maritalstatus);
		sqlsKit.addData("seclevel", StringKit.null2Str(ob.getString("saleLevel")));			//安全级别  
		sqlsKit.setWhere("workcode", StringKit.null2Str(ob.getString("id")));				//员工编号
		sqlsKit.setOperateType(SqlOperateType.UPDATE);
		return sqlsKit;
	}
	
	/**
	 * 更新人员直接上级
	 * @param id
	 * @param ob
	 * @return
	 */
	public SqlsKit updateManagerid(String id, JSONObject ob){
		SqlsKit sqlsKit = SqlsKit.me();
		sqlsKit.clear();		
		sqlsKit.setTableName("HrmResource");
		String managerid = "";
		Record resourceRecord = this.resourceCache.getRecordByCode(ob.getString("leader"));
		if(resourceRecord!=null)
			managerid = StringKit.null2o(resourceRecord.get("ID"));
		sqlsKit.addData("managerid", managerid);
		sqlsKit.setWhere("workCode", id);
		sqlsKit.setOperateType(SqlOperateType.UPDATE);
		return sqlsKit;
	}
	
	/**
	 * 更新人员自定义信息
	 * @param id
	 * @param ob
	 * @return
	 */
	public SqlsKit insertOtherInfo(String id, JSONObject ob){
		SqlsKit sqlsKit = SqlsKit.me();
		sqlsKit.clear();	
		sqlsKit.setTableName("CUS_FIELDDATA");
		sqlsKit.addData("SCOPE", "HrmCustomFieldByInfoType");
		sqlsKit.addData("SCOPEID", "-1");
		String pid = "";
		Record resourceRecord = this.resourceCache.getRecordByCode(id);
		if(resourceRecord!=null)
			pid = StringKit.null2o(resourceRecord.get("ID"));
		sqlsKit.addData("ID", pid);
		sqlsKit.addData("FIELD0", StringKit.null2o(ob.get("otheSysRoleId")));
		sqlsKit.addData("FIELD1", StringKit.null2o(ob.get("partId")));
		sqlsKit.setOperateType(SqlOperateType.INSERT);
		return sqlsKit;
	}
	
	/**
	 * 清空全部人员自定义信息
	 * @return
	 */
	public SqlsKit deleteOtherInfo(){
		SqlsKit sqlsKit = SqlsKit.me();
		sqlsKit.clear();	
		sqlsKit.setTableName("CUS_FIELDDATA");
		sqlsKit.setWhere("SCOPE", "HrmCustomFieldByInfoType");
		sqlsKit.setWhere("SCOPEID", "-1");
		sqlsKit.setOperateType(SqlOperateType.DELETE);
		return sqlsKit;
	}
	
	@Override
	protected void refreshCache() {
		this.resourceCache.reload();
		this.educattiionLevelCache.reload();
		this.departmentCache.reload();
		this.jobTitleCache.reload();
		try{new ResourceComInfo().removeResourceCache();}catch (Exception e) {}
	}
	
	public static void main(String[] args) {
		System.out.println();
	}
	
}
